﻿using System;
using System.Collections.Generic;
using Bogus;
using Microsoft.EntityFrameworkCore;
using RescueApp.Data;
using RescueApp.Models;

namespace RescueApp.CreateDb
{
    class Program
    {
        private static Random random = new Random(); // 初始化 Random 实例

        static void Main(string[] args)
        {
            var db = new RescueContext();
            try
            {
                db.Database.EnsureDeleted();
                db.Database.EnsureCreated();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return;
            }

            // 生成救援申请假数据
            var rescueApplyFaker = new RescueSystemFakers().RescueApplyFaker;
            var rescueApplies = rescueApplyFaker.Generate(50);
            db.RescueApplies.AddRange(rescueApplies);
            db.SaveChanges(); // 首先保存 RescueApply 数据，以生成 RescueID

            // 生成救援派遣假数据
            var rescueDispatchFaker = new RescueSystemFakers().RescueDispatchFaker;
            var rescueDispatches = rescueDispatchFaker.Generate(50);

            // 确保 RescueID 引用的是已存在的 RescueApply 实例
            if (rescueApplies.Any())
            {
                foreach (var dispatch in rescueDispatches)
                {
                    dispatch.RescueID = rescueApplies[random.Next(rescueApplies.Count)].RescueID;
                }
            }

            // 将 rescueDispatches 添加到 DbContext
            db.RescueDispatches.AddRange(rescueDispatches);

            // 保存数据到数据库
            try
            {
                db.SaveChanges();
                Console.WriteLine("假数据插入成功！");
            }
            catch (DbUpdateException ex)
            {
                Console.WriteLine($"插入数据失败：{ex.InnerException?.Message ?? ex.Message}");
            }
        }
    }
}